package com.andnux.android.network;

import android.content.Context;
import android.content.SharedPreferences;

import com.andnux.android.MainApp;

import java.util.Locale;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class RetrofitClient {

    private static RetrofitClient client;
    private final Retrofit retrofit;

    public RetrofitClient() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        HttpTokenInterceptor tokenInterceptor = new HttpTokenInterceptor();
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(loggingInterceptor)
                .addNetworkInterceptor(tokenInterceptor)
                .build();
        SharedPreferences preferences = MainApp.getApp().getSharedPreferences("config", Context.MODE_PRIVATE);
        String url = preferences.getString("url", "");
        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(String.format(Locale.CHINA, "http://%s:8080", url))
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
    }

    public static RetrofitClient getInstance() {
        if (client == null) {
            synchronized (RetrofitClient.class) {
                if (client == null) {
                    client = new RetrofitClient();
                }
            }
        }
        return client;
    }

    public DesignCloudApi getServerApi() {
        return retrofit.create(DesignCloudApi.class);
    }
}
